#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , udpSocket(new QUdpSocket(this))//创建udp套接字
{
    ui->setupUi(this);
    setWindowTitle("8000");
    //    绑定对应的端口号
    udpSocket->bind(QHostAddress::Any,8000);
//    组播用ipv4
//    udpSocket->bind(QHostAddress::AnyIPv4,9000);
//    加入组播
    udpSocket->joinMulticastGroup(QHostAddress("224.0.1"));
//  离开组播

    //    链接信号和槽函数，读取对应客户端发来的信息,有消息发送会触发ready read信号
    connect(udpSocket,&QUdpSocket::readyRead,this,&Widget::dealMsg);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::dealMsg()
{
    char buf[1024];
    QHostAddress ip;
    quint16 port;
    //接受信息
    qint64 len = udpSocket->readDatagram(buf,sizeof(buf),&ip,&port);
    if(len>0){
            //    显示信息
        QString str = QString("[%1:%2] %3")
                .arg(ip.toString())
                .arg(port)
                .arg(buf);
        ui->textEditRead->append(str);
    }

}


void Widget::on_buttonSend_clicked()
{
    QString ip = ui->lineEditIP->text();
    quint16 port = ui->lineEditPort->text().toInt();
    QString str = ui->textEditWrite->toPlainText();
//    写入套接字
    udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port);
}

void Widget::on_buttonClose_clicked()
{
    close();
}
